<?php
use Illuminate\Database\Eloquent\SoftDeletingTrait;

class Total extends Eloquent
{
	use SoftDeletingTrait;

	public $timestamps   = true;
	protected $dates     = ['deleted_at'];
	protected $table     = 'customer_payment';
	protected $validator = null;

	public function getAll($type){
		$customers = Customer::whereType($type)->orderBy('name')->get();
		$result = array();

		foreach($customers as $customer){
			$result[$customer->id]['name'] = $customer->name;

			$dept = DB::table('customer_payment')
							->whereCustomer($customer->id)
							->whereNull('deleted_at')
							->whereType('dept')
							->sum('total');

			$total = DB::table('order')
							->whereCustomer($customer->id)
							->whereNull('deleted_at')
							->sum('total');

			$total += DB::table('customer_payment')
							->whereCustomer($customer->id)
							->whereNull('deleted_at')
							->whereType('total')
							->sum('total');

			$payment = DB::table('customer_payment')
							->whereCustomer($customer->id)
							->whereNull('deleted_at')
							->whereType('payment')
							->sum('total');

			$refund = DB::table('customer_payment')
							->whereCustomer($customer->id)
							->whereNull('deleted_at')
							->whereType('refund')
							->sum('total');

			$result[$customer->id]['dept']      = $dept;
			$result[$customer->id]['total']     = $total;
			$result[$customer->id]['payment']   = $payment;
			$result[$customer->id]['refund']    = $refund;
			$result[$customer->id]['sale']      = $total - $refund;
			$result[$customer->id]['remaining'] = $dept + $total - $payment - $refund;
		}

		return $result;
	}
}